<template>
  <s-clean-layout :title="pageTitle" navbar="normal">
    <view class="event-type-container">
      <!-- 添加事件类型按钮 -->
      <view class="add-type-btn" @tap="showAddTypeInput">
        <text class="add-type-text">添加{{ pageTitle }}</text>
        <view class="favorite-icon">
          <uni-icons type="heart" size="18" color="#FF9800"></uni-icons>
        </view>
      </view>

      <!-- 类型网格 -->
      <view class="type-grid">
        <view
          class="type-item"
          v-for="(type, index) in typeList"
          :key="index"
          @tap="selectType(type.name)"
        >
          <view class="type-content">
            <image class="type-icon" :src="type.icon" mode="aspectFit"></image>
            <text class="type-name">{{ type.name }}</text>
          </view>
          <view class="edit-icon" v-if="isEditMode" @tap.stop="showEditTypeInput(type, index)">
            <uni-icons type="compose" size="16" color="#2196F3"></uni-icons>
          </view>
          <view class="delete-icon" v-if="isEditMode" @tap.stop="deleteType(index)">
            <uni-icons type="closeempty" size="16" color="#E57373"></uni-icons>
          </view>
        </view>
      </view>
      
      <!-- 底部间距，确保内容不被底部按钮遮挡 -->
      <view style="height: 120rpx;"></view>

      <!-- 底部编辑/完成按钮 -->
      <view class="bottom-edit-button" @tap="toggleEditMode">
        <text>{{ isEditMode ? '完成' : '编辑' + pageTitle }}</text>
      </view>

      <!-- 添加类型弹窗 -->
      <view class="add-type-popup" v-if="showAddTypePopup">
        <view class="popup-mask" @tap="closeAddTypePopup"></view>
        <view class="popup-content">
          <view class="popup-header">
            <text class="popup-title">{{ isEdit ? '编辑' + pageTitle : '添加' + pageTitle }}</text>
            <view class="close-btn" @tap="closeAddTypePopup">
              <uni-icons type="close" size="20" color="#999"></uni-icons>
            </view>
          </view>
          <view class="popup-body">
            <view class="input-group">
              <text class="input-label">类型名称</text>
              <input class="type-input" v-model="newTypeName" placeholder="请输入类型名称" maxlength="4" />
            </view>
            <view class="input-group">
              <text class="input-label">选择图标</text>
              <view class="icon-grid">
                <view
                  class="icon-item"
                  v-for="(icon, index) in iconList"
                  :key="index"
                  :class="{ 'selected': selectedIconIndex === index }"
                  @tap="selectIcon(index)"
                >
                  <image class="icon-image" :src="icon" mode="aspectFit"></image>
                </view>
              </view>
            </view>
          </view>
          <view class="popup-footer">
            <button class="cancel-btn" @tap="closeAddTypePopup">取消</button>
            <button class="confirm-btn" @tap="addNewType">确定</button>
          </view>
        </view>
      </view>
    </view>
  </s-clean-layout>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import CommApi from '@/sheep/api/comm/comm';

const emit = defineEmits(['type-selected']);

const props = defineProps({
  businType: { type: String, default: '' },
  pageTitle: { type: String, default: '类型管理' }
});

const businType = ref(props.businType);
const pageTitle = ref(props.pageTitle);

// 编辑模式状态
const isEditMode = ref(false);

// 类型列表
const typeList = ref([]);

// 选中的类型
const selectedType = ref('');

// 添加类型弹窗相关
const showAddTypePopup = ref(false);
const newTypeName = ref('');
const selectedIconIndex = ref(0);
const isEdit = ref(false);
const editingTypeId = ref(null);

// 图标列表
const iconList = ref([
  'https://bpic.51yuansu.com/pic3/cover/03/68/36/65bf26bcd52d0_260.jpg?x-oss-process=image/resize,h_360,m_lfit/sharpen,100',
  'https://t9.baidu.com/it/u=224810020,2012841530&fm=193',
  '/static/icons/event-types/book.png',
  '/static/icons/event-types/business.png',
  '/static/icons/event-types/game.png',
  '/static/icons/event-types/movie.png',
  '/static/icons/event-types/chess.png',
  '/static/icons/event-types/ktv.png',
  '/static/icons/event-types/food.png',
  '/static/icons/event-types/wine.png',
  '/static/icons/event-types/hiking.png',
  '/static/icons/event-types/cycling.png',
  '/static/icons/event-types/shopping.png',
  '/static/icons/event-types/meeting.png',
  '/static/icons/event-types/gift.png',
  '/static/icons/event-types/other.png'
]);

// 获取事件类型列表
const getEventTypeList = async () => {
  try {
    uni.showLoading({
      title: '加载中...'
    });
    
    const res = await CommApi.queryUserBusinCategory({
      businType: businType.value
    });
    
    uni.hideLoading();
    
    if (res.code === 0 && res.data) {
      typeList.value = res.data.map(item => ({
        id: item.id,
        name: item.categoryName,
        icon: item.iconUrl || '/static/icons/event-types/other.png'
      }));
    } else {
      uni.showToast({
        title: '获取类型失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('获取类型列表失败:', error);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  }
};

// 切换编辑模式
const toggleEditMode = () => {
  isEditMode.value = !isEditMode.value;
};

// 删除类型
const deleteType = async (index) => {
  const typeId = typeList.value[index].id;
  
  try {
    uni.showLoading({
      title: '删除中...'
    });
    
    const res = await CommApi.deleteUserBusinCategory({
      id: typeId,
      businType: businType.value
    });
    
    uni.hideLoading();
    
    if (res.code === 0) {
      typeList.value.splice(index, 1);
      uni.showToast({
        title: '删除成功',
        icon: 'success'
      });
    } else {
      uni.showToast({
        title: '删除失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error('删除类型失败:', error);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  }
};

// 选择类型
const selectType = (type) => {
  // 编辑模式下点击类型不执行选择操作
  if (isEditMode.value) return;
  
  // 查找选中类型的完整信息
  const selectedTypeInfo = typeList.value.find(item => item.name === type);
  if (!selectedTypeInfo) return;
  
  selectedType.value = type;
  
  // 存储完整的类型信息到本地，包括id
  uni.setStorageSync('selectedEventType', {
    id: selectedTypeInfo.id,
    name: selectedTypeInfo.name,
    icon: selectedTypeInfo.icon
  });
  
  // 触发事件通知父组件
  emit('type-selected', {
    id: selectedTypeInfo.id,
    name: selectedTypeInfo.name,
    icon: selectedTypeInfo.icon
  });
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

// 显示添加类型输入框
const showAddTypeInput = () => {
  isEdit.value = false;
  editingTypeId.value = null;
  showAddTypePopup.value = true;
  newTypeName.value = '';
  selectedIconIndex.value = 0;
};

// 显示编辑类型输入框
const showEditTypeInput = (type, index) => {
  isEdit.value = true;
  editingTypeId.value = type.id;
  showAddTypePopup.value = true;
  newTypeName.value = type.name;
  
  // 查找图标在列表中的索引
  const iconIndex = iconList.value.findIndex(icon => icon === type.icon);
  selectedIconIndex.value = iconIndex >= 0 ? iconIndex : 0;
};

// 关闭添加类型弹窗
const closeAddTypePopup = () => {
  showAddTypePopup.value = false;
};

// 选择图标
const selectIcon = (index) => {
  selectedIconIndex.value = index;
};

// 添加新类型
const addNewType = async () => {
  if (!newTypeName.value.trim()) {
    uni.showToast({
      title: '请输入类型名称',
      icon: 'none'
    });
    return;
  }
  
  // 检查类型名称是否已存在
  const exists = typeList.value.some(item => 
    item.name === newTypeName.value.trim() && 
    (!isEdit.value || item.id !== editingTypeId.value)
  );
  
  if (exists) {
    uni.showToast({
      title: '该类型名称已存在',
      icon: 'none'
    });
    return;
  }
  
  try {
    uni.showLoading({
      title: isEdit.value ? '更新中...' : '添加中...'
    });
    
    let res;
    if (isEdit.value) {
      res = await CommApi.updateUserBusinCategory({
        id: editingTypeId.value,
        categoryName: newTypeName.value.trim(),
        businType: businType.value,
        iconUrl: iconList.value[selectedIconIndex.value],
        sortOrder: 0
      });
    } else {
      res = await CommApi.addUserBusinCategory({
        categoryName: newTypeName.value.trim(),
        businType: businType.value,
        iconUrl: iconList.value[selectedIconIndex.value],
        sortOrder: 0
      });
    }
    
    uni.hideLoading();
    
    if (res.code === 0) {
      if (isEdit.value) {
        // 更新现有类型
        const index = typeList.value.findIndex(item => item.id === editingTypeId.value);
        if (index !== -1) {
          typeList.value[index] = {
            id: editingTypeId.value,
            name: newTypeName.value.trim(),
            icon: iconList.value[selectedIconIndex.value]
          };
        }
      } else {
        // 添加新类型
        typeList.value.push({
          id: res.data,
          name: newTypeName.value.trim(),
          icon: iconList.value[selectedIconIndex.value]
        });
      }
      
      closeAddTypePopup();
      
      uni.showToast({
        title: isEdit.value ? '更新成功' : '添加成功',
        icon: 'success'
      });
    } else {
      uni.showToast({
        title: isEdit.value ? '更新失败' : '添加失败',
        icon: 'none'
      });
    }
  } catch (error) {
    uni.hideLoading();
    console.error(isEdit.value ? '更新类型失败:' : '添加类型失败:', error);
    uni.showToast({
      title: '网络异常，请稍后重试',
      icon: 'none'
    });
  }
};

onMounted(() => {
  // 获取 businType 参数
  const pages = getCurrentPages();
  const currentPage = pages[pages.length - 1];
  if (currentPage.options && currentPage.options.businType) {
    businType.value = currentPage.options.businType;
  }
  // 动态设置标题
  pageTitle.value = businType.value === 'RELATIONSHIP' ? '关系类型管理' : (props.pageTitle || '类型管理');
  // 获取事件类型列表
  getEventTypeList();
});

watch(() => businType.value, getEventTypeList);
</script>

<style lang="scss" scoped>
.event-type-container {
  min-height: 100vh;
  background-color: #f5f5f5;
  padding-bottom: 40rpx;
  position: relative;
}

/* 移除原有的header样式 */
.header {
  display: none;
}

/* 底部编辑按钮样式 */
.bottom-edit-button {
  position: fixed;
  bottom: 20rpx;
  left: 50%;
  transform: translateX(-50%);
  width: 90%;
  height: 90rpx;
  background-color: #2196F3;
  color: #fff;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32rpx;
  font-weight: 500;
  z-index: 100;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.2);
  border-radius: 45rpx;
  margin-bottom: env(safe-area-inset-bottom);
}

.add-type-btn {
  margin: 20rpx;
  padding: 30rpx;
  background-color: #fff;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  position: relative;
}

.add-type-text {
  font-size: 32rpx;
  color: #2196F3;
}

.favorite-icon {
  position: absolute;
  right: 30rpx;
  top: 50%;
  transform: translateY(-50%);
}

.type-grid {
  display: flex;
  flex-wrap: wrap;
  padding: 0 10rpx;
}

.type-item {
  width: 25%;
  padding: 10rpx;
  box-sizing: border-box;
  position: relative;
}

.type-content {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 20rpx 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

// 修改编辑图标位置到左上角
.edit-icon {
  position: absolute;
  top: 10rpx;
  left: 10rpx;
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
}

// 修改删除图标位置到右上角，并调整位置更靠右
.delete-icon {
  position: absolute;
  top: 10rpx;
  right: 10rpx; // 确保删除按钮在右上角
  width: 40rpx;
  height: 40rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2;
  background-color: rgba(255, 255, 255, 0.8);
  border-radius: 50%;
}

.type-icon {
  width: 60rpx;
  height: 60rpx;
  margin-bottom: 10rpx;
}

.type-name {
  font-size: 28rpx;
  color: #FF9800;
}

// 添加类型弹窗样式
.add-type-popup {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 999;
  display: flex;
  align-items: center;
  justify-content: center;
}

.popup-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
}

.popup-content {
  position: relative;
  width: 80%;
  max-width: 600rpx; // 添加最大宽度
  background-color: #fff;
  border-radius: 12rpx;
  overflow: hidden;
  z-index: 1000;
}

.popup-header {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 30rpx;
  position: relative;
  border-bottom: 1px solid #f0f0f0;
}

.popup-title {
  font-size: 32rpx;
  font-weight: 500;
  color: #333;
}

.close-btn {
  position: absolute;
  right: 30rpx;
  top: 30rpx;
}

.popup-body {
  padding: 30rpx;
}

.input-group {
  margin-bottom: 30rpx;
}

.input-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

// 修复输入框样式，防止超出边界
.type-input {
  width: 100%;
  height: 80rpx;
  border: 1px solid #eee;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  box-sizing: border-box; // 添加这一行确保padding不会导致宽度超出
}

.icon-grid {
  display: flex;
  flex-wrap: wrap;
  margin: 0 -10rpx;
}

.icon-item {
  width: 25%;
  padding: 10rpx;
  box-sizing: border-box;
}

.icon-item .icon-image {
  width: 100%;
  height: 100rpx;
  border: 1px solid #eee;
  border-radius: 8rpx;
  padding: 10rpx;
  box-sizing: border-box;
}

.icon-item.selected .icon-image {
  border-color: #007AFF;
  background-color: rgba(0, 122, 255, 0.1);
}

.popup-footer {
  display: flex;
  border-top: 1px solid #f0f0f0;
}

.popup-footer button {
  flex: 1;
  height: 90rpx;
  line-height: 90rpx;
  text-align: center;
  font-size: 30rpx;
  border-radius: 0;
  margin: 0;
}

.cancel-btn {
  background-color: #f5f5f5;
  color: #666;
}

.confirm-btn {
  background-color: #007AFF;
  color: #fff;
}
</style>
